package com.lzs.lzscodesandbox.controller;

import com.lzs.lzscodesandbox.JavaCodeSandboxTemplateImpl;
import com.lzs.lzscodesandbox.model.ExecuteCodeRequest;
import com.lzs.lzscodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {

    // 定义鉴权请求头
    private static final String AUTH_REQUEST_HEADER = "auth";
    // 定义鉴权密钥
    private static final String AUTH_REQUEST_SECRET = "secretKey";


    @Resource
    private JavaCodeSandboxTemplateImpl javaCodeSandboxTemplateImpl;

    /**
     * 执行代码
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                           HttpServletResponse response){
        // 最基本的认证权限
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!authHeader.equals(AUTH_REQUEST_SECRET)) {// 得到请求头不等于密钥的话
            response.setStatus(403);// 禁止
            return null;
        }
        if (executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }
        return javaCodeSandboxTemplateImpl.executeCode(executeCodeRequest);
    }
}
